﻿using System;
using IdentityModel.Client;
using IdentityModel;
using System.Net.Http;
using Newtonsoft.Json.Linq;

namespace MyClient
{
    class Program
    {
        static void Main(string[] args)
        {
            // discover endpoints from metadata
            var client = new HttpClient();
            var disco = client.GetDiscoveryDocumentAsync("http://localhost:5000").Result;
            if (disco.IsError)
            {
                Console.WriteLine(disco.Error);
                return;
            }
            // request token
            var tokenResponse = client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
            {
                Address = disco.TokenEndpoint,

                ClientId = "client",
                ClientSecret = "secret",
                Scope = "api1"
            }).Result;

            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                return;
            }

            Console.WriteLine(tokenResponse.Json);
            /*
             Token request validation success, {
                 "ClientId": "client",
                 "GrantType": "client_credentials",
                 "Scopes": "api1",
                 "Raw": {
                   "scope": "api1",
                   "grant_type": "client_credentials",
                   "client_id": "client",
                   "client_secret": "***REDACTED***"
                 }
               }
             */
            // call api
            var client1 = new HttpClient();
            client1.SetBearerToken(tokenResponse.AccessToken);

            var response =  client1.GetAsync("http://localhost:5001/identity").Result;
            if (!response.IsSuccessStatusCode)
            {
                Console.WriteLine(response.StatusCode);
            }
            else
            {
                var content =  response.Content.ReadAsStringAsync().Result;
                Console.WriteLine(JArray.Parse(content));
            }
            Console.WriteLine("Hello World!");
        }

        
         

    }
}
